<template>
	<view class="container">
		<!-- #ifndef H5 -->
		<uni-nav-bar v-if="tabCurrent == 1||tabCurrent == 3" fixed="true" status-bar="true" :title="title"></uni-nav-bar>
		<!-- #endif -->
		<Home ref="home" v-show="tabCurrent == 0" :scroll-top="scrollTop"></Home>
		<Category :style="tabCurrent == 1?'':'display:none'"></Category>
		<Order v-if="tabCurrent == 3"></Order>
		<Center ref="center" v-show="tabCurrent == 4"></Center>
		<newTabbar @current="current" :act="tabCurrent"></newTabbar>
		<uni-popup ref="popup" type="center">
			<view class="screenBox">
				<view class="top">
					<text class="a">国家普惠社区APP</text>
					<text class="b">下载</text>
				</view>
				<view class="bottom">
					<text class="text">下载国家普惠社区APP，即可使用更多功能，体验更好的优质服务。</text>
					<view class="btn" @tap="downApp">立即下载</view>
					<text class="lebal">建议在wifi环境下载哦~</text>
				</view>
				<view class="close" @tap="close">
					<image src="../../static/images/center/close.png" mode=""></image>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import Home from "@/pages/index/home.vue"
	import Category from "@/pages/category/category.vue"
	import Order from "@/pages/order/order.vue"
	import Center from "@/pages/center/center.vue"
	import newTabbar from "@/components/new-tabbar/new-tabbar.vue"
	import uniNavBar from "@/components/uni-nav-bar/uni-nav-bar.vue"
	import utils from "@/common/utils.js"
	import uniPopup from '@/components/uni-popup/uni-popup.vue'
	import wechat from '@/common/wechat.js'
	import {
		appVersion
	} from "@/api/app.js"
	export default {
		components: {
			Home,
			Category,
			Center,
			Order,
			newTabbar,
			uniNavBar,
			uniPopup
		},
		data() {
			return {
				title: "",
				tabCurrent: 0,
				//#ifdef APP-PLUS
				apkUrl: '',
				//#endif
				scrollTop: 0
			};
		},
		onLoad(option) {
			// app端判断引导页
			//#ifdef  APP-PLUS
			let launchFlag = uni.getStorageSync('launchFlag')
			if (!launchFlag) {
				uni.redirectTo({
					url: "/pages/guidePages/guidePages"
				})
				return
			}
			//#endif
			uni.setNavigationBarColor({
				frontColor: "#ffffff"
			})
			//#ifdef H5
			//扫描个人邀请码后提示下载app
			let _this = this
			this.$nextTick(function() {
				if (!uni.getStorageSync('appDownload') && uni.getStorageSync('isPerson')) {
					_this.$refs.popup.open()
					uni.setStorageSync('appDownload', true)
					uni.setStorageSync('advertisingShow', false)
					uni.removeStorageSync("isPerson")
				} else {
					uni.setStorageSync('advertisingShow', true)
					uni.removeStorageSync("isPerson")
				}
			})
			//#endif
			//#ifdef APP-PLUS
			this.$nextTick(function() {
				uni.setStorageSync('advertisingShow', true)
				uni.removeStorageSync("isPerson")
			})
			//#endif
			if (option.current) {
				this.tabCurrent = Number(option.current)
			}
			// h5扫描邀请二维码后缓存参数，并跳转登录绑定关系
			//#ifdef H5
			if (option.uid && option.uk) {
				let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
				let QRCodeRout = "/" + routes[routes.length - 1].route //获取当前页面路由
				uni.setStorageSync("QRCodeRout", QRCodeRout)
				uni.setStorageSync("pid", option.uid)
				uni.setStorageSync("pos", option.uk)
				uni.navigateTo({
					url: `/pages/login/login`
				})
			}
			//#endif
			// app扫描邀请二维码后缓存参数，并跳转登录绑定关系
			//#ifdef APP-PLUS
			if (option.scene) {
				let options = utils.urlDecode(option)
				uni.setStorageSync("pid", options.uid) //统一改成uid
				uni.setStorageSync("pos", options.uk)
				uni.navigateTo({
					url: `/pages/login/login`
				})
			}
			//#endif
			// h5分享
			// #ifdef H5
			if (!uni.getStorageSync("Authori-zation")) {
				if (this.tabCurrent == 0) {
					wechat.share(uni.getStorageSync("share")[0].title, "", window.location.href + '?current=0', uni.getStorageSync(
						"share")[0].url)
				} else if (this.tabCurrent == 1) {
					wechat.share(uni.getStorageSync("share")[3].title, "", window.location.href + '?current=1', uni.getStorageSync(
						"share")[3].url)
				}
			} else {
				if (this.tabCurrent == 0) {
					wechat.share(uni.getStorageSync("share")[0].title, "", window.location.href + '?current=0&uid=' + uni.getStorageSync(
						"userInfo").uid + "&uk=1", uni.getStorageSync("share")[0].url)
				} else if (this.tabCurrent == 1) {
					wechat.share(uni.getStorageSync("share")[3].title, "", window.location.href + '?current=1&uid=' + uni.getStorageSync(
						"userInfo").uid + "&uk=1", uni.getStorageSync("share")[3].url)
				}
			}
			// #endif
		},
		onShow() {
			if (this.tabCurrent == 0) {
				this.$nextTick(function() {
					this.$refs.home.getIndex()
				})
			} else if (this.tabCurrent == 3) {
				if (!uni.getStorageSync("Authori-zation")) {
					this.tabCurrent = 0
				} else {
					this.tabCurrent = 10;
					this.$nextTick(() => {
						this.tabCurrent = 3;
					})
				}
			} else if (this.tabCurrent == 4) {
				this.$nextTick(function() {
					this.$refs.center.getUserInfo()
				})
			}
			// app版本控制
			// #ifdef APP-PLUS
			appVersion({}).then(res => {
				let _this = this
				let platform = uni.getSystemInfoSync().platform
				let server_version = res.data.config.version;
				let is_update = res.data.config.is_update;
				let ios_server_version = res.data.ios_config.ios_version;
				let is_ios_update = res.data.ios_config.is_ios_update;
				let currTimeStamp = Date.parse(new Date()) / 1000;
				let last_version = plus.runtime.versionCode
				let last_version_time = uni.getStorageSync('last_version_time')
				if (platform == 'android') {
					// android更新
					if (last_version && last_version_time) {
						if (server_version > last_version) {
							_this.apkUrl = res.data.config.app_url
							let tipTimeLength = 3600;
							if ((last_version_time + tipTimeLength) > currTimeStamp) {
								//避免多次提醒，不要更新
							} else {
								//重新设置时间戳
								uni.setStorageSync('last_version_time', currTimeStamp)
								//进行版本型号的比对 以及下载更新请求
								_this.checkVersionToLoadUpdate(server_version, last_version, is_update);
							}
						}
					} else {
						uni.setStorageSync('last_version_time', currTimeStamp)
					}
				} else if (platform == 'ios') {
					// ios更新
					if (last_version && last_version_time) {
						if (ios_server_version > last_version) {
							let appleId = res.data.ios_config.ios_appleid
							let tipTimeLength = 3600;
							if ((last_version_time + tipTimeLength) > currTimeStamp) {
								//避免多次提醒，不要更新
							} else {
								//重新设置时间戳
								if (is_ios_update == 1) {
									uni.setStorageSync('last_version_time', currTimeStamp)
									//跳转app store 更新版本
									uni.showModal({
										content: "有新的版本发布，如不更新，会影响用户使用，请立即更新？",
										showCancel: false,
										confirmText: "立即更新",
										success(re) {
											if (re.confirm) {
												plus.runtime.launchApplication({
													action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`
												}, function(e) {
													console.log('Open system default browser failed: ' + e.message);
												});
											} else if (re.cancel) {}
										}
									})
								} else {
									uni.setStorageSync('last_version_time', currTimeStamp)
									//跳转app store 更新版本
									uni.showModal({
										content: "有新的版本发布，是否去App Store更新？",
										confirmText: "更新",
										success(re) {
											if (re.confirm) {
												plus.runtime.launchApplication({
													action: `itms-apps://itunes.apple.com/cn/app/id${appleId}?mt=8`
												}, function(e) {
													console.log('Open system default browser failed: ' + e.message);
												});
											} else if (re.cancel) {}
										}
									})
								}
							}
						}
					} else {
						uni.setStorageSync('last_version_time', currTimeStamp)
					}
				}
			})
			// #endif
		},
		onPageScroll({
			scrollTop
		}) {
			// 传入scrollTop值并触发所有easy-loadimage组件下的滚动监听事件
			this.scrollTop = scrollTop;
		},
		onShareAppMessage() { //分享 
			if (!uni.getStorageSync("Authori-zation")) {
				if (this.tabCurrent == 0) {
					return {
						title: uni.getStorageSync("share")[0].title,
						path: '/pages/index/index?current=0',
						imageUrl: uni.getStorageSync("share")[0].url
					}
				} else if (this.tabCurrent == 1) {
					return {
						title: uni.getStorageSync("share")[3].title,
						path: '/pages/index/index?current=1',
						imageUrl: uni.getStorageSync("share")[3].url
					}
				}
			} else {
				if (this.tabCurrent == 0) {
					return {
						title: uni.getStorageSync("share")[0].title,
						path: '/pages/index/index?current=0&uid=' + uni.getStorageSync("userInfo").uid + "&uk=1",
						imageUrl: uni.getStorageSync("share")[0].url
					}
				} else if (this.tabCurrent == 1) {
					return {
						title: uni.getStorageSync("share")[3].title,
						path: '/pages/index/index?current=1&uid=' + uni.getStorageSync("userInfo").uid + "&uk=1",
						imageUrl: uni.getStorageSync("share")[3].url
					}
				}

			}
		},
		methods: {
			close() {
				this.$refs.popup.close()
			},
			copy() {
				uni.setClipboardData({
					data: 'http://download.ditanshequ.vip/pages/public/appDownLoad',
					success: function() {
						uni.showToast({
							icon: "none",
							title: "复制成功"
						})
					}
				});
			},
			downApp() {
				uni.navigateTo({
					url: "/pages/public/appDownLoad"
				})
				this.close()
			},
			current(e) {
				this.title = e.title
				this.tabCurrent = e.current
				if (this.tabCurrent == 0) {
					this.$refs.home.getIndex()
				}
				if (this.tabCurrent == 4) {
					this.$refs.center.getUserInfo()
				}
			},
			// #ifdef APP-PLUS
			/**
			 * 进行版本型号的比对 以及下载更新请求
			 * @param {Object} server_version 服务器最新 应用版本号
			 * @param {Object} curr_version 当前应用版本号
			 */
			checkVersionToLoadUpdate: function(server_version, last_version, is_update) {
				let _this = this
				if (server_version > last_version) {
					if (is_update == 1) {
						plus.nativeUI.confirm('有新的版本发布，如不更新，会影响用户使用，请立即更新？', function(event) {
							var tapIndex = event.index;
							switch (tapIndex) {
								case 0:
									var downloadApkUrl = _this.apkUrl;
									var dtask = plus.downloader.createDownload(downloadApkUrl, {}, function(d, status) {
										// 下载完成  
										if (status == 200) {
											plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, {}, function(error) {
												uni.showToast({
													title: '安装失败',
													duration: 1500
												});
											})
										} else {
											uni.showToast({
												title: '更新失败',
												duration: 1500
											});
										}
									});
									dtask.start();
									var showLoading = plus.nativeUI.showWaiting("正在下载");
									dtask.addEventListener("statechanged", function(task, status) {
										switch (task.state) {
											case 1: // 开始  
												showLoading.setTitle("正在下载...");
												break;
											case 2: // 已连接到服务器
												showLoading.setTitle("已连接到服务器");
												break;
											case 3:
												var a = task.downloadedSize / task.totalSize * 100;
												showLoading.setTitle(parseInt(a) + "%");
												break;
											case 4: // 下载完成  
												uni.removeStorageSync('launchFlag')
												plus.nativeUI.closeWaiting();
												break;
										}
									});
									break;
							}
						}, "版本更新", ["立即更新"]);
					} else {
						plus.nativeUI.confirm('有新的版本发布，是否立即进行新版本下载？', function(event) {
							var tapIndex = event.index;
							switch (tapIndex) {
								case 0:
									var downloadApkUrl = _this.apkUrl;
									var dtask = plus.downloader.createDownload(downloadApkUrl, {}, function(d, status) {
										// 下载完成  
										if (status == 200) {
											plus.runtime.install(plus.io.convertLocalFileSystemURL(d.filename), {}, {}, function(error) {
												uni.showToast({
													title: '安装失败',
													duration: 1500
												});
											})
										} else {
											uni.showToast({
												title: '更新失败',
												duration: 1500
											});
										}
									});
									dtask.start();
									var showLoading = plus.nativeUI.showWaiting("正在下载");
									dtask.addEventListener("statechanged", function(task, status) {
										switch (task.state) {
											case 1: // 开始  
												showLoading.setTitle("正在下载...");
												break;
											case 2: // 已连接到服务器
												showLoading.setTitle("已连接到服务器");
												break;
											case 3:
												var a = task.downloadedSize / task.totalSize * 100;
												showLoading.setTitle(parseInt(a) + "%");
												break;
											case 4: // 下载完成  
												uni.removeStorageSync('launchFlag')
												plus.nativeUI.closeWaiting();
												break;
										}
									});
									break;
								case 1:
									console.log('稍后更新');
									break;
							}
						}, "版本更新", ["立即更新", "稍后进行"]);
					}

				}
			},
			//#endif
		}
	};
</script>

<style>
	page {
		background-color: #f5f5f5 !important;
	}
</style>
<style scoped lang="scss">
	.screenBox {
		.top {
			width: 565rpx;
			height: 290rpx;
			background: url(https://inclusivecommunity.oss-cn-chengdu.aliyuncs.com/attach/2020-09/638fe202009181753396393.png) no-repeat;
			background-size: 100% 100%;
			border-radius: 8rpx 8rpx 0px 0px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			align-items: center;
			color: #fff;

			.a {
				font-size: 40rpx;
				font-weight: 500;
				text-shadow: 2rpx 6rpx 7rpx rgba(0, 0, 0, 0.2);
			}

			.b {
				margin-top: 26rpx;
				font-size: 50rpx;
				font-weight: 500;
				text-shadow: 3rpx 8rpx 10rpx rgba(0, 0, 0, 0.2);
			}
		}

		.bottom {
			width: 565rpx;
			height: 400rpx;
			padding: 50rpx 55rpx 0;
			box-sizing: border-box;
			background: #FFFFFF;
			border-radius: 0px 0px 8rpx 8rpx;
			display: flex;
			flex-direction: column;

			.text {
				margin-top: 6rpx;
				width: 100%;
				font-size: 24rpx;
				color: #333;
				line-height: 40rpx;
				text-align: justify;
				word-wrap: break-word;
				white-space: normal;
				word-break: break-all;

				.url {
					text-decoration: underline;
				}
			}

			.btn {
				width: 340rpx;
				height: 70rpx;
				background: #4BCC82;
				box-shadow: 3rpx 8rpx 13rpx 0px rgba(59, 194, 116, 0.3);
				border-radius: 35rpx;
				text-align: center;
				line-height: 70rpx;
				font-size: 32rpx;
				color: #fff;
				margin: 70rpx auto 30rpx;
			}

			.lebal {
				font-size: 24rpx;
				color: #999;
				margin: 0 auto;
			}
		}

		.close {
			display: flex;
			flex-direction: column;
			align-items: center;
			padding-top: 40rpx;

			image {
				width: 20rpx;
				height: 20rpx;
				padding: 25rpx;
				border-radius: 50%;
				background-color: rgba(255, 255, 255, .8);
			}
		}
	}
</style>
